<template>
<div>
  <div class="box box-custom">
    <div class="box-header with-border">
       <h3 class="box-title">问题管理</h3>
       <button type="button" class="btn btn-custom pull-right" v-on:click="showAdd()">新建问题</button>
    </div>
    <div class="box-body custom-tree-container">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th class="textCenter" style="min-width: 260px;">分类</th>
            <th class="textCenter">问题列表</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <el-tree
                highlight-current
                accordion
                :expand-on-click-node="false"
                :data="questionsTree"
                node-key="id">
                <div class="custom-tree-node" slot-scope="{ node, data }" @click="() => showQuestionsList(node, data)">
                  <span class="table_td">{{ data.name }}</span>
                </div>
              </el-tree>
            </td>
            <td>
              <el-table class="table table-bordered"
              style="width: 100%;"
              size="mini"
              border
              stripe
              highlight-current-row
              empty-text="请选择包含有问题的二级分类"
              :data="showList"
              >
                <el-table-column prop="quName" label="题目" width="500">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="text"
                    @click="showPreview(scope.$index, scope.row)">
                      <i class="el-icon-view"></i> 预览
                    </el-button>
                    <el-button
                    size="mini"
                    type="text"
                    @click="showEdit(scope.$index, scope.row)">
                      <i class="el-icon-edit"></i> 编辑
                    </el-button>
                    <el-button
                    size="mini"
                    type="text"
                    @click="delQuestion(scope.$index, scope.row)">
                      <span class="danger"><i class="el-icon-delete"></i> 删除</span>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <el-dialog width="60%"
  :title="dialogTitle"
  :visible.sync="dialogVisible"
  :before-close="handleClose">
    <form class="form-horizontal">
      <div class="form-group">
        <label class="col-sm-2 control-label">问题</label>
        <div class="col-sm-10">
          <input class="form-control" type="text" v-model="formData.quName" />
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">编号</label>
        <div class="col-sm-10">
          <input class="form-control" type="text" v-model="formData.item" />
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">排列顺序</label>
        <div class="col-sm-10">
          <input class="form-control" type="number" v-model="formData.orderBy" />
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">描述</label>
        <div class="col-sm-10">
          <textarea class="form-control" rows="3" cols="20" name="quNote" v-model="formData.quNote">{{formData.quNote}}</textarea>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">插图</label>
        <div class="col-sm-5">
          <input type="file" name="img" accept="image/*" v-on:change="addImg($event)">
        </div>
        <div class="col-sm-5">
          <img id="previewImg" :src="formData.imgUrl" width="100"/>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-2 control-label pointer" v-on:click="addAnswerItem()">
          <label class="">答案项 </label> <i class="fa fa-plus-square"></i>
        </div>
        <div class="col-sm-9 border padding10">
          <div class="form-inline bottom10" v-for="(item, key) in currentAnswer">
            <div class="input-group">
              <span class="input-group-addon">选项{{key + 1}}</span>
              <input type="text" class="form-control" placeholder="" v-model="item.optionName">
            </div>
            <div class="input-group">
              <span class="input-group-addon">分值</span>
              <input type="number" class="form-control" placeholder="" v-model="item.optionScore">
            </div>
            <div class="input-group pointer" v-on:click="removeAnswerItem(key)">
              <i class="fa fa-minus-square"></i>
            </div>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">补充选项 [json数组字符串]</label>
        <div class="col-sm-10">
          <textarea class="form-control" rows="3" cols="20" name="quNote" v-model="formData.otherOptions" placeholder='[{"question":"名称","inputType":"text|textarea|radio|checkbox|select","answer":"[]"}]'>{{formData.otherOptions}}</textarea>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">所属分类</label>
        <div class="col-sm-10">
          <el-cascader
            size="small"
            expand-trigger="hover"
            :options="categoryTree"
            v-model="formData.categoryId">
          </el-cascader>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">禁用</label>
        <div class="col-sm-10">
          <div class="checkbox form-control">
            <label>
              <input type="checkbox" v-model="formData.disabled" />
            </label>
          </div>
          <!-- el-switch class="form-control" v-model="formData.disabled"></el-switch -->
        </div>
      </div>
      <div class="textCenter">
        <button type="button" class="btn btn-custom" v-on:click="onSubmit()">保存</button>
      </div>
    </form>
  </el-dialog>
  <el-dialog width="60%"
  title="查看问题"
  :visible.sync="previewDialogVisible"
  :before-close="handleClose">
    <showQuestionView ref="showQuestion" :questionData="showQuestionData"></showQuestionView>
  </el-dialog>
</div>
</template>
<script>
import showQuestionView from './previewQuestion.vue'

export default {
  name: 'questions',
  data () {
    return {
      categoryTree: [],
      questionsTree: [],
      // 当前查看的分类索引值
      selectCategory: [],
      // 当前选中分类的问题列表
      showList: [],
      // 当前被编辑的问题索引
      editorQuestionIndex: -1,
      // 编辑问卷
      dialogVisible: false,
      dialogTitle: '',
      formData: {},
      // 当前编辑的问题选答项列表
      currentAnswer: [],
      // 预览问卷
      previewDialogVisible: false,
      showQuestionData: {}
    }
  },
  components:{
    showQuestionView
  },
  methods: {
    getQuestionCategory () {
      this.$http.get('question/listCategory').then(
        response => {
          this.questionsTree = response.data.data
          this.setCategoryTree()
        }
      )
    },
    addQuestion () {
      this.$http.post('question/saveQuestion', this.formData).then(
        response => {
          alert(response.data.message)
          if (this.editorQuestionIndex >= 0){
            // console.log(this.editorQuestionIndex)
            this.showList[this.editorQuestionIndex] = response.data.data
            // 更新数据，保证页面同步刷新
            this.showList = JSON.parse(JSON.stringify(this.showList));
          } else{
            this.showList.push(response.data.data)
          }
          // console.log(this.showList)
          this.editorQuestionIndex = -1
          this.formData = {}
          this.dialogVisible = false
        }
      )
    },
    updataQuestion () {
    },
    delQuestion (index, row) {
      if (confirm('确认删除？') === false ) return false
      this.$http.delete('question/deleteQuestion?id=' + row.id).then(
        response => {
          alert(response.data.message)
          this.showList.splice(index, 1)
        }
      )
    },
    showQuestionsList (node, data) {
      if (node.level === 1 && !node.isLeaf) { return }
      this.$http.get('question/listQuestion?categoryId=' + data.id).then(
        response => {
          this.showList = data.questionsList = response.data.data
        }
      )
      this.selectCategory = []
      this.selectCategory.push(node.parent.data.id)
      this.selectCategory.push(data.id)
    },
    showAdd () {
      this.dialogTitle = '新建问题'
      this.formData = {}
      this.formData.categoryId = []
      if (this.selectCategory[0] >=0 && this.selectCategory[1] >= 0) {
        this.formData.categoryId.push(this.selectCategory[0])
        this.formData.categoryId.push(this.selectCategory[1])
      }
      this.currentAnswer = []
      this.addAnswerItem()
      this.dialogVisible = true
    },
    showEdit (index, row) {
      this.dialogTitle = '修改问题'
      this.editorQuestionIndex = index
      this.formData = {}
      this.formData.id = row.id
      this.formData.quName = row.quName
      this.formData.item = row.item
      this.formData.quNote = row.quNote
      this.formData.otherOptions = row.otherOptions
      this.formData.imgUrl = row.file
      this.formData.categoryId = []
      this.formData.categoryId.push(this.selectCategory[0])
      this.formData.categoryId.push(this.selectCategory[1])
      this.currentAnswer = []
      row.quRadios.map((item)=>{this.currentAnswer.push(item)})
      this.formData.disabled = row.disabled
      this.formData.orderBy = row.orderBy
      this.dialogVisible = true
    },
    addAnswerItem () {
      this.currentAnswer.push({optionName: '', optionScore: 0})
    },
    removeAnswerItem (key) {
      this.currentAnswer.splice(key, 1)
    },
    addImg (ev) {
      let fileObj = ev.target.files[0]
      if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
        alert("请选择图片")
        return
      }
      // 创建读取文件的对象
      var reader = new FileReader();

      //为文件读取成功设置事件  
      reader.onload = function(e) {  
        $('#previewImg').attr('src', e.target.result)
      }

      // 正式读取文件
      reader.readAsDataURL(fileObj)
      
      //加入文件对象
      let formFile = new FormData()
      formFile.append("file", fileObj)
      this.$http.post('file/uploadFiles', formFile).then(
        response => {
          this.formData.file = this.formData.imgUrl = response.data.data[0].url
          this.formData.imgFullPath = response.data.data[0].fullPath
          ev.target.value = null
        }
      )
    },
    onSubmit () {
      // this.formData.treeId = this.formData.categoryId
      this.formData.categoryId = this.formData.categoryId[1]
      this.formData.quRadios = this.currentAnswer
      // this.formData.id ? this.updataQuestion() : this.addQuestion()
      this.addQuestion()
    },
    setCategoryTree () {
      for (let i = 0; i < this.questionsTree.length; i++ ) {
        let category = []
        for (let j = 0; j < this.questionsTree[i].children.length; j++ ) {
          category.push({label: this.questionsTree[i].children[j].name, value: this.questionsTree[i].children[j].id})
        }
        this.categoryTree.push({label: this.questionsTree[i].name, value: this.questionsTree[i].id, children: category})
      }
    },
    handleClose (done) {
      this.$confirm('确认关闭？').then(_ => { done() }).catch(_ => {})
    },
    showPreview (index, row) {
      this.showQuestionData = row
      this.showQuestionData.category = this.getTreeByCategoryId(this.categoryTree, row.categoryId)
      this.previewDialogVisible = true
    },
    getTreeByCategoryId (tree, categoryId) {
      for (let i = 0; i < tree.length; i++) {
        for (let j = 0; j < tree[i].children.length; j++) {
          if (categoryId === tree[i].children[j].value) {
            return [{id: tree[i].value, name: tree[i].label}, {id: tree[i].children[j].value, name: tree[i].children[j].label}];
          }
        }
      }
      return [{id: '', name: ''}, {id: '', name: ''}];
    }
  },

  beforeCreate () {},
  created () {},
  beforeMount () {},
  mounted () {
    this.getQuestionCategory()
  },
  beforeUpdate () {},
  updated () {},
  beforeDestroy () {},
  destroyed () {}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
